//
//  WLHttpManager.m
//  WanLian
//
//  Created by muzhuang on 2018/9/12.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLHttpManager.h"
#import "WLFileSocketManager.h"

@implementation WLHttpManager

+ (AFHTTPSessionManager*)httpManager
{
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:BASEURL]];
        
        //超时时间
        manager.requestSerializer.timeoutInterval = 10;
        //设置请求格式
        manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //设置返回格式
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    });
    return manager;
}
+ (AFHTTPSessionManager *)getBackGroundManager {
    static AFHTTPSessionManager *backGroundManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *appID = [[NSBundle mainBundle] bundleIdentifier];
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:appID];
//        configuration.networkServiceType = NSURLNetworkServiceTypeBackground;
//        configuration.HTTPShouldUsePipelining = YES;
        configuration.timeoutIntervalForResource = 100000;
        backGroundManager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:BASEURL] sessionConfiguration:configuration];
        
//        backGroundManager.requestSerializer.timeoutInterval = 180;
        
        //超时时间
//        backGroundManager.requestSerializer.timeoutInterval = 10;
//        //设置请求格式
//        backGroundManager.requestSerializer = [AFJSONRequestSerializer serializer];
//        //设置返回格式
//        backGroundManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    });
    return backGroundManager;
}
//返回数据格式及类型
//message,"***",__NSCFString或者NSNull
//object,<null>,NSNull或者是对象、数组，解析时需要判断
//count,0,__NSCFNumber
//bresult,0,__NSCFBoolean
//url,<null>,NSNull或者__NSCFString
//errorTag,0,__NSCFNumber
+(void)WLRequestMethod:(RequsetMethod)method urlStr:(NSString *)urlStr withParamsDic:(NSDictionary *)parameters success:(void (^)(NSDictionary *successDict))success failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure error:(void (^)(NSError *error))err inView:(UIView *)showView
{
//#warning
    showView = nil;
    urlStr = [WLCommonTool formateURLString:urlStr];
    if (![WLCommonTool isConnectionAvailable]) {
        [showView showHUDMessage:@"似乎已断开与互联网的连接"];
        if (err) {
            NSError *error = [[NSError alloc] initWithDomain:@"无网络连接" code:DoNotHaveNetCode userInfo:nil];
            err(error);
        }
        return;
    }
    if (showView != nil) {
        [showView showHUDProgressHUD];
    }
    AFHTTPSessionManager *manager = [WLHttpManager httpManager];
//    [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    NSString *strSession = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SESSION];
    if (strSession != nil)
    {
        NSString *cookie = [NSString stringWithFormat:@"JSESSIONID=%@",strSession];
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
//        NSString *session = [NSString stringWithFormat:@"%@",[strCookie componentsSeparatedByString:@"="].lastObject];
        [manager.requestSerializer setValue:strSession forHTTPHeaderField:@"sessionId"];
    }
//    WLLog(@"header:%@",manager.requestSerializer.HTTPRequestHeaders);
    switch (method) {
        case RequestTypePost:
        {
            [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSError *err = nil;
                NSDictionary *dictRet = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&err];
                WLLog(@"\nURL:%@\nrequestParameter:%@\njson:\n%@",task.currentRequest.URL,[self logDic:parameters],[self logDic:dictRet]);
                if (!err)
                {
                    BOOL isSuccess = [dictRet[@"bresult"] boolValue];
                    if (isSuccess == NO) {
                        if (dictRet[@"code"] && [dictRet[@"code"] integerValue] == 0) {
                            isSuccess = YES;
                        }
                    }
                    if (isSuccess)
                    {
                        //获取cookie保存
//                        NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//                        NSString *JSESSIONID = @"";
//                        for (NSHTTPCookie *cookie in cookies.cookies) {
//                            WLLog(@"cookie:%@",cookie);
//                            if ([cookie.name isEqualToString:@"JSESSIONID"])
//                            {
//                                JSESSIONID=cookie.value;
//                                [[NSUserDefaults standardUserDefaults] setObject:JSESSIONID forKey:USER_SESSION];
//                            }
//                        }
                        
//                        NSHTTPURLResponse* response = (NSHTTPURLResponse* )task.response;
////                        WLLog(@"headerFields:%@",response.allHeaderFields);
//                        NSString *dataCookie = response.allHeaderFields[@"Set-Cookie"];
//                        if (dataCookie != nil)
//                        {
//                            NSString *cookie = [NSString stringWithFormat:@"%@",[[dataCookie componentsSeparatedByString:@";"]objectAtIndex:0]];
//                            [[NSUserDefaults standardUserDefaults] setObject:cookie forKey:@"userCookie"];
//                        }
                        
                        //返回成功数据
                        success(dictRet);
                    }
                    else
                    {
                        NSString *strMsg = dictRet[@"message"];
                        if (strMsg == nil) {
                            NSString *msg = dictRet[@"msg"];
                            failure(msg, [dictRet[@"code"] integerValue]);
                        } else {
                            if ([dictRet[@"errorTag"] integerValue]==10001)//用户未登录或登录已过期
                            {
                                failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                                [WLCommonTool goToLogin];
                            }
                            else if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
                            {
                                failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                            }
                            else
                            {
                                failure(@"请求失败",[dictRet[@"errorTag"] integerValue]);
                            }
                        }
                        
                    }
                }
                else
                {
                    success(nil);
                }
                
                [showView hideHUD];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                if (err) {
                    err(error);
                }
                [showView hideHUD];
                if (showView != nil) {
                    [showView showHUDMessage:@"请求失败"];
                }
                WLLog(@"\nURL:%@\nrequestParameter:%@\nerror:\n%@",task.currentRequest.URL,[self logDic:parameters],error.localizedDescription);
            }];
        }
            break;
        case RequestTypeGet:
        {
            [manager GET:urlStr parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSError *err = nil;
                NSDictionary *dictRet = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&err];
                WLLog(@"\nURL:\nrequestParameter:%@\njson:\n%@",[self logDic:parameters],[self logDic:dictRet]);
                if (!err)
                {
                    BOOL isSuccess = [dictRet[@"bresult"] boolValue];
                    if (isSuccess == NO) {
                        if (dictRet[@"code"] && [dictRet[@"code"] integerValue] == 0) {
                            isSuccess = YES;
                        }
                    }
                    if (isSuccess)
                    {
                        //获取cookie保存
//                        NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
//                        NSString *JSESSIONID = @"";
//                        for (NSHTTPCookie *cookie in cookies.cookies) {
//                            WLLog(@"cookie:%@",cookie);
//                            if ([cookie.name isEqualToString:@"JSESSIONID"])
//                            {
//                                JSESSIONID=cookie.value;
//                                [[NSUserDefaults standardUserDefaults] setObject:JSESSIONID forKey:USER_SESSION];
//                            }
//                        }
                        
                        
//                        NSHTTPURLResponse* response = (NSHTTPURLResponse* )task.response;
//                        WLLog(@"headerFields:%@",response.allHeaderFields);
//                        NSString *dataCookie = response.allHeaderFields[@"Set-Cookie"];
//                        if (dataCookie != nil)
//                        {
//                            NSString *cookie = [NSString stringWithFormat:@"%@",[[dataCookie componentsSeparatedByString:@";"]objectAtIndex:0]];
//                            [[NSUserDefaults standardUserDefaults] setObject:cookie forKey:@"userCookie"];
//                        }
                        //返回成功数据
                        success(dictRet);
                    }
                    else
                    {
                        NSString *strMsg = dictRet[@"message"];
                        if (strMsg == nil) {
                            NSString *msg = dictRet[@"msg"];
                            failure(msg, [dictRet[@"code"] integerValue]);
                        } else {
                            if ([dictRet[@"errorTag"] integerValue]==10001)//用户未登录或登录已过期
                            {
                                failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                                [WLCommonTool goToLogin];
                            }
                            else if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
                            {
                                failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                            }
                            else
                            {
                                failure(@"请求失败",[dictRet[@"errorTag"] integerValue]);
                            }
                        }
                    }
                }
                else
                {
                    success(nil);
                }
                
                [showView hideHUD];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                err(error);
                [showView hideHUD];
                if (showView != nil) {
                    [showView showHUDMessage:@"请求失败"];
                }
            }];
        }
            break;
            
        default:
            break;
    }
}

+ (NSURLSessionDataTask *)WLUpDownloadPost:(NSString *)URLString
                                parameters:(NSDictionary *)parameters
                 constructingBodyWithBlock:( void (^)(id <AFMultipartFormData> formData))block
                                  progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                                   success:(void (^)(NSDictionary *successDict))success
                                   failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                                     error:(void (^)(NSError *error))err
                                    inView:(UIView *)showView
{
    if (![WLCommonTool isConnectionAvailable])
    {
        if (showView != nil) {
            [showView showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        else
        {
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            [window showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        err(nil);
        return nil;
    }
    if (showView != nil) {
        [showView showHUDProgressHUD];
    }
    AFHTTPSessionManager *manager = [WLHttpManager httpManager];
//    [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    NSString *strSession = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SESSION];
    if (strSession != nil)
    {
        NSString *cookie = [NSString stringWithFormat:@"JSESSIONID=%@",strSession];
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
        [manager.requestSerializer setValue:strSession forHTTPHeaderField:@"sessionId"];
    }
    NSURLSessionDataTask *upDownLoadTask = [manager POST:URLString parameters:parameters constructingBodyWithBlock:block progress:uploadProgress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *err = nil;
        NSDictionary *dictRet = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&err];
        WLLog(@"\nURL:\nrequestParameter:%@\njson:\n%@",[self logDic:parameters],[self logDic:dictRet]);
        if (!err)
        {
            BOOL isSuccess = [dictRet[@"bresult"] boolValue];
            if (isSuccess == NO) {
                if (dictRet[@"code"] && [dictRet[@"code"] integerValue] == 0) {
                    isSuccess = YES;
                }
            }
            if (isSuccess)
            {
                success(dictRet);
            }
            else
            {
                NSString *strMsg = dictRet[@"message"];
                if (strMsg == nil) {
                    NSString *msg = dictRet[@"msg"];
                    failure(msg, [dictRet[@"code"] integerValue]);
                } else {
                    if ([dictRet[@"errorTag"] integerValue]==10001)//用户未登录或登录已过期
                    {
                        failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                        [WLCommonTool goToLogin];
                    }
                    else if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
                    {
                        failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                    }
                    else
                    {
                        failure(@"请求失败",[dictRet[@"errorTag"] integerValue]);
                    }
                }
            }
        }
        else
        {
            success(nil);
        }
        [showView hideHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);
        [showView hideHUD];
        if (showView != nil) {
            [showView showHUDMessage:@"请求失败"];
        }
        WLLog(@"\nURL:%@\nrequestParameter:%@\nerror:\n%@",task.currentRequest.URL,[self logDic:parameters],error.localizedDescription);
    }];
    
    return upDownLoadTask;
}

// log NSSet with UTF8
// if not ,log will be \Uxxx
+ (NSString *)logDic:(NSDictionary *)dic
{
    if (![dic count]) {
        return nil;
    }
    NSString *tempStr1 =
    [[dic description] stringByReplacingOccurrencesOfString:@"\\u"
                                                 withString:@"\\U"];
    NSString *tempStr2 =
    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 =
    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString *str = [NSPropertyListSerialization propertyListWithData:tempData options:NSPropertyListImmutable format:NULL error:NULL];
//    [NSPropertyListSerialization propertyListFromData:tempData
//                                     mutabilityOption:NSPropertyListImmutable
//                                               format:NULL
//                                     errorDescription:NULL];
    return str;
}


/** 自带host的网络请求  */

+ (NSURLSessionDataTask *)WLBackgroundUploadPost:(NSString *)URLString
                                      parameters:(NSDictionary *)parameters
                       constructingBodyWithBlock:( void (^)(id <AFMultipartFormData> formData))block
                                        progress:(void (^)(NSProgress *uploadProgress))uploadProgress
                                         success:(void (^)(NSDictionary *successDict))success
                                         failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                                           error:(void (^)(NSError *error))err
                                          inView:(UIView *)showView
{
    if (![WLCommonTool isConnectionAvailable])
    {
        if (showView != nil) {
            [showView showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        else
        {
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            [window showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        err(nil);
        return nil;
    }
    if (showView != nil) {
        [showView showHUDProgressHUD];
    }
//    AFHTTPSessionManager *manager = [WLHttpManager httpManager];
    AFHTTPSessionManager *manager = [WLHttpManager getBackGroundManager];
    //    [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    NSString *strSession = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SESSION];
    if (strSession != nil)
    {
        NSString *cookie = [NSString stringWithFormat:@"JSESSIONID=%@",strSession];
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
        [manager.requestSerializer setValue:strSession forHTTPHeaderField:@"sessionId"];
    }
    
    if (![URLString hasPrefix:@"http"]) {
        NSString *host = [WLCommonTool getHost];
        URLString = [NSString stringWithFormat:@"%@%@",host, URLString];
    }
    NSURLSessionDataTask *upDownLoadTask = [manager POST:URLString parameters:parameters constructingBodyWithBlock:block progress:uploadProgress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *err = nil;
        NSDictionary *dictRet = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&err];
        WLLog(@"\nURL:\nrequestParameter:%@\njson:\n%@",[self logDic:parameters],[self logDic:dictRet]);
        if (!err)
        {
            BOOL isSuccess = NO;
            if (dictRet[@"code"]) {
                if ([dictRet[@"code"] intValue] == 0) {
                    isSuccess = YES;
                }
            } else if (dictRet[@"bresult"]) {
                isSuccess = [dictRet[@"bresult"] boolValue];
            }
            
            if (isSuccess)
            {
                success(dictRet);
            }
            else
            {
                NSString *strMsg = nil;
                if (dictRet[@"msg"]) {
                    strMsg = dictRet[@"msg"];
                } else if (dictRet[@"message"]) {
                    strMsg = dictRet[@"message"];
                }
                if ([dictRet[@"errorTag"] integerValue]==10001)//用户未登录或登录已过期
                {
                    failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                    [WLCommonTool goToLogin];
                }
                else if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
                {
                    failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                }
                else
                {
                    failure(@"请求失败",[dictRet[@"errorTag"] integerValue]);
                }
            }
        }
        else
        {
            success(nil);
        }
        [showView hideHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (err) {
            err(error);
        }
        [showView hideHUD];
        if (showView != nil) {
            [showView showHUDMessage:@"请求失败"];
        }
        WLLog(@"\nURL:%@\nrequestParameter:%@\nerror:\n%@",task.currentRequest.URL,[self logDic:parameters],error.localizedDescription);
    }];
    
    return upDownLoadTask;
}


/** 自带host的网络请求  */

+ (NSURLSessionDataTask *)WLBackgroundDownloadGet:(NSString *)URLString
                                      parameters:(NSDictionary *)parameters
                                        progress:(void (^)(NSProgress *uploadProgress))downloadProgress
                                         success:(void (^)(NSDictionary *successDict))success
                                         failure:(void (^)(NSString *errorMsg, NSInteger errorTag))failure
                                           error:(void (^)(NSError *error))err
                                          inView:(UIView *)showView
{
    if (![WLCommonTool isConnectionAvailable])
    {
        if (showView != nil) {
            [showView showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        else
        {
            UIWindow *window = [[UIApplication sharedApplication] keyWindow];
            [window showHUDMessage:@"似乎已断开与互联网的连接"];
        }
        err(nil);
        return nil;
    }
    if (showView != nil) {
        [showView showHUDProgressHUD];
    }
    AFHTTPSessionManager *manager = [WLHttpManager getBackGroundManager];
    //    [manager.requestSerializer setHTTPShouldHandleCookies:YES];
    NSString *strSession = [[NSUserDefaults standardUserDefaults] objectForKey:USER_SESSION];
    if (strSession != nil)
    {
        NSString *cookie = [NSString stringWithFormat:@"JSESSIONID=%@",strSession];
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
        [manager.requestSerializer setValue:strSession forHTTPHeaderField:@"sessionId"];
    }
    
    if (![URLString hasPrefix:@"http"]) {
        NSString *host = [WLCommonTool getHost];
        URLString = [NSString stringWithFormat:@"%@%@",host, URLString];
    }
    
//    [manager downloadTaskWithRequest:<#(nonnull NSURLRequest *)#> progress:downloadProgress destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//        <#code#>
//    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
//        <#code#>
//    }];
    NSURLSessionDataTask *downloadTask = [manager GET:URLString parameters:parameters progress:downloadProgress success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSError *err = nil;
        NSDictionary *dictRet = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&err];
        WLLog(@"\nURL:\nrequestParameter:%@\njson:\n%@",[self logDic:parameters],[self logDic:dictRet]);
        if (!err)
        {
            BOOL isSuccess = NO;
            if (dictRet[@"code"]) {
                if ([dictRet[@"code"] intValue] == 0) {
                    isSuccess = YES;
                }
            } else if (dictRet[@"bresult"]) {
                isSuccess = [dictRet[@"bresult"] boolValue];
            }
            
            if (isSuccess)
            {
                success(dictRet);
            }
            else
            {
                NSString *strMsg = nil;
                if (dictRet[@"msg"]) {
                    strMsg = dictRet[@"msg"];
                } else if (dictRet[@"message"]) {
                    strMsg = dictRet[@"message"];
                }
                if ([dictRet[@"errorTag"] integerValue]==10001)//用户未登录或登录已过期
                {
                    failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                    [WLCommonTool goToLogin];
                }
                else if (strMsg != nil&&[strMsg isKindOfClass:[NSNull class]]==NO)
                {
                    failure(dictRet[@"message"],[dictRet[@"errorTag"] integerValue]);
                }
                else
                {
                    failure(@"请求失败",[dictRet[@"errorTag"] integerValue]);
                }
            }
        }
        else
        {
            success(nil);
        }
        [showView hideHUD];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (err) {
            err(error);
        }
        [showView hideHUD];
        if (showView != nil) {
            [showView showHUDMessage:@"请求失败"];
        }
        WLLog(@"\nURL:%@\nrequestParameter:%@\nerror:\n%@",task.currentRequest.URL,[self logDic:parameters],error.localizedDescription);
    }];
    
    return downloadTask;
}
@end
